package it.polimi.travelDream.ejb.servlet;

import it.polimi.travelDream.ejb.interfaces.TransportationMgrRemote;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class EditTravelServler
 */
@WebServlet("/EditTravelServler")
public class EditTravelServler extends HttpServlet {
	private static final long serialVersionUID = 1L;
	DateFormat format = new SimpleDateFormat("dd/MM/yyyy");   
	@EJB
	TransportationMgrRemote tmr;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditTravelServler() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		Map<String, String[]> mappa = request.getParameterMap();
		format.setLenient(false);
		/*Empty Fields Check*/
		if (mappa.get("type")[0].isEmpty() || mappa.get("from")[0].isEmpty() || mappa.get("to")[0].isEmpty() || mappa.get("out")[0].isEmpty() || mappa.get("in")[0].isEmpty() ||	mappa.get("cost")[0].isEmpty())
		 {
			request.setAttribute("message","Empty fields.");
			request.getRequestDispatcher("/BPEditTravel.jsp").forward(request, response); 
		 }
		else
		{	
			
			try {
				 format.parse(mappa.get("out")[0]);
				 format.parse(mappa.get("in")[0]);
				 Integer.parseInt(mappa.get("cost")[0]);
				 if (
						 format.parse(mappa.get("out")[0]).before(format.parse(mappa.get("in")[0])) && 
						 !format.parse(mappa.get("out")[0]).equals(format.parse(mappa.get("in")[0])) )
						 
						 {
		String id=mappa.get("id")[0];
		String type=mappa.get("type")[0];
		String from=mappa.get("from")[0];
		String to=mappa.get("to")[0];
		String in=mappa.get("in")[0];
		String out=mappa.get("out")[0];
		String cost=mappa.get("cost")[0];
		
		tmr.modifyTransportation(id, type, from, to, out, in, cost);}
			} catch (ParseException e) {
				 
				 request.setAttribute("message","Date must be dd/mm/yyyy");
					request.getRequestDispatcher("/BPEditTravel.jsp").forward(request, response); 
				 
			 }
		
		
	}
	}
}
